<?php

require_once 'Basic.php';

class VehicleCreate extends BasicEntity {

  private static $actionName = "Create";
  
  private static $plateField = "plate";
  private static $kmInitField = "kmInit";
  private static $vencSeguroField = "vencSeguro";
  private static $yearField = "year";
  private static $priceCostField = "priceCost";
  private static $modelVehicleField = "modelVehicle";
  private static $subsidiaryVehicleField = "subsidiaryVehicle";
  
  private $modelVehicle;
  private $subsidiaryVehicle;
  
  public function __construct() {
  
    $db = new DBUtils;
    
    try {
      $db->connect();
 
      $this->modelVehicle = array();
      $db->runQuery("select idModelo,nome,marca from Modelo");
      for($item = $db->getItem(); $item !== null; $item = $db->getItem()) {
        $this->modelVehicle[$item->idModelo] = $item->marca . " " . $item->nome;
      }
      
      $this->subsidiaryVehicle = array();
      $db->runQuery("select idFilial,nome from Filial");
      for($item = $db->getItem(); $item !== null; $item = $db->getItem()) {
        $this->subsidiaryVehicle[$item->idFilial] = $item->nome;
      }
          
      $db->close(true);
    }
    catch(DBError $e) {
      $db->close(false);
      logMessage($e->errors, "DBError");
      return "Falha no banco de dados. O erro foi reportado.";
    }  
  
    $this->fields = array(
      new FormField(true, VehicleCreate::$plateField, "Placa", new FormFieldPlate()),
      new FormField(true, VehicleCreate::$kmInitField, "Kilometragem Inicial", new FormFieldAbsNumber()),
      new FormField(false, VehicleCreate::$vencSeguroField, "Vencimento do Seguro", new FormFieldDate()),
      new FormField(false, VehicleCreate::$yearField, "Ano", new FormFieldAbsNumber(1970)),
      new FormField(false, VehicleCreate::$priceCostField, "Pre&ccedil;o de Custo", new FormFieldPrice()),        
      new FormField(true, VehicleCreate::$modelVehicleField, "Modelo", new FormFieldChoice($this->modelVehicle)),
      new FormField(true, VehicleCreate::$subsidiaryVehicleField, "Filial", new FormFieldChoice($this->subsidiaryVehicle))
      
    );
    $this->processFields();
  }
  
  public function actionDescription() {
    return VehicleCreate::$actionName;
  }
  
  public function actionCreate($userInput) {  
		foreach($this->fields as $k => $v) {
		  $$k = $v->value();
		}
	
    if($priceCost !== null) {
      $priceCost = str_replace(",",".",$priceCost);
    }
    $plate = str_replace("-","",$plate);
    
		$db = new DBUtils();
		 
		try {
     $db->connect();
     
     $db->runQuery("select idVeiculo from Veiculo where placa = ?", array($plate));
     if($db->getItem() !== null) {
      $this->fields[VehicleCreate::$plateField]->setValid(false);
      return "Ve&iacute;culo com placa ${plate} j&aacute; cadastrado.";
     }
     
     $db->runQuery("insert into Veiculo (placa, kilometragemInicial, kilometragemAtual, vencimentoSeguro, ano, custoCompra, modelo, filial) values(?, ?, ?, ?, ?, ?, ?, ?)",
                    array($plate, $kmInit, $kmInit, $vencSeguro, $year, $priceCost, intval($modelVehicle), intval($subsidiaryVehicle)));
     
     $db->close(true);
    }
    catch(DBError $e) {
     $db->close(false);
     logMessage($e->errors, "VehicleCreate");
     return "Falha no banco de dados. O erro foi reportado.";
    }
    
    return true;
  }
}

mustBeEmployee();
correctStdFormGET();
$page = new Page("Cadastro de Veículo");
$VehicleCreate = new VehicleCreate();
$form = new StdForm($VehicleCreate, $_GET, $_POST,
        "<p>" . htmlentities("Campos em negrito são obrigatórios.") . "</p>",
        "<p>" . htmlentities("Cadastro realizado com sucesso.") . "</p>",
        "VehicleCreate.php");
$form->processForm();
$page->addContent($form->getHtml());
echo $page->getHtml();